/*
 * handleTreadForC.c
 *
 *  Created on: 2010-3-11
 *      Author: abc
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#define   MAXBUF   256

int   port=5000;
char  *  multicast_addr= "224.0.1.1 ";

void * multiThreadForC(void* p){
	  int   s,n;
	  struct   sockaddr_in   srv,cli;
	  int   cli_len=sizeof(cli);
	  struct   ip_mreq   mreq;
	  char   buf[MAXBUF];
	  int multiPort = 8189;
	  bzero(&srv,sizeof(srv));
	  srv.sin_family=AF_INET;
	  srv.sin_addr.s_addr=htonl(INADDR_ANY);
	  srv.sin_port=htons(multiPort);

	  if((s=socket(AF_INET,SOCK_DGRAM,0)) <0)
	  {
	    perror( "Opening   socket ");
	    return   0;
	  }

	  if(bind(s,(struct   sockaddr*)&srv,sizeof(srv)) <0)
	  {
	    perror( "bind ");
	    return   0;
	  }

	  mreq.imr_multiaddr.s_addr=inet_addr(multicast_addr);
	  mreq.imr_interface.s_addr=htonl(INADDR_ANY);

	  if(setsockopt(s,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq,sizeof(mreq)) <0)
	  {
	    perror( "setsockopt:   IP_ADD_MEMBERSHIP ");
	    return   0;
	  }

	  while(1)
	  {
	    if((n=recvfrom(s,buf,MAXBUF,0,(struct   sockaddr*)&cli,&cli_len)) <0)
	    {
	      perror( "recvfrom ");
	      return   0;
	    }
	    else
	    {
	      buf[n]=0;
	      fprintf(stdout, "host chatroom   %s   : %s\n ",inet_ntoa(cli.sin_addr),buf);
	    }
	  }
	  return   1;
}
